package zplh.com.commonlibrary.module;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Looper;

import java.io.File;

import zplh.com.commonlibrary.networker.FileDownLoadSubscriber;
import zplh.com.commonlibrary.networker.NetWorker;
import zplh.com.commonlibrary.utils.LogUtils;
import zplh.com.commonlibrary.utils.ScriptUtils;
import zplh.com.commonlibrary.utils.ToastUtils;

/**
 * <pre>
 *     author : YONGHAOZENG
 *     e-mail : 1007687534@qq.com
 *     time   : 2018/08/06
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class DownLoadModule {
    public DownLoadModule() {
    }
    public void downLoadFile(Context context,File file,String url) {
        ProgressDialog dialog = new ProgressDialog(context);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setCancelable(false);
        dialog.setMax(1000);
        dialog.setMessage("下载中");
        dialog.show();
        new Thread(new Runnable() {

            @Override
            public void run() {
                Looper.prepare();

                FileDownLoadSubscriber subscriber = new FileDownLoadSubscriber(file) {
                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        dialog.dismiss();
                        ToastUtils.showToastError((Activity) context, "下载出现问题" + t.getMessage());
                    }

                    @Override
                    public void onSuccess(File file) {
                        super.onSuccess(file);
                        ((Activity) context).runOnUiThread(() -> dialog.setMessage("正在安装"));
                        ScriptUtils.installScript(file);
                        dialog.dismiss();

                    }

                    @Override
                    public void onProgress(float current, float total) {
                        super.onProgress(current, total);
                        LogUtils.d("下载容量", current / total * 1000 + "");
                        dialog.setProgress(Math.round(current / total * 1000));

                    }
                };

                NetWorker.getInstance().downLoad(subscriber, url);
            }
        }).start();

    }
}
